package cn.turboinfo.fuyang.api.domain.common.usecase.user;

import cn.turboinfo.fuyang.api.domain.common.component.common.EntityObjectHelper;
import cn.turboinfo.fuyang.api.domain.common.service.user.UserTypeRelService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.common.EntityObjectType;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.UserTypeRel;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 列出用户拥有的所有用户类型关系
 *
 * @author hai
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class CommonListUserTypeUseCase extends AbstractUseCase<CommonListUserTypeUseCase.InputData, CommonListUserTypeUseCase.OutputData> {

    private final UserTypeRelService userTypeRelService;

    private final EntityObjectHelper entityObjectHelper;

    @Override
    protected OutputData doAction(InputData inputData) {
        Long userId = inputData.getUserId();

        List<UserTypeRel> userTypeRelList = userTypeRelService.findByUserId(userId);

        entityObjectHelper.resolveFriendlyEntityObjectName(userTypeRelList,
                rel -> Pair.of(rel.getObjectType(), rel.getObjectId()),
                UserTypeRel::setObjectName);

        entityObjectHelper.resolveFriendlyEntityObjectName(userTypeRelList,
                rel -> Pair.of(getReferenceType(rel.getObjectType()), rel.getReferenceId()),
                UserTypeRel::setReferenceName);

        return OutputData.builder()
                .userTypeRelList(userTypeRelList)
                .build();
    }

    private EntityObjectType getReferenceType(EntityObjectType objectType) {
        switch (objectType) {
            case STAFF: {
                return EntityObjectType.COMPANY;
            }
            default:
                return objectType;
        }
    }

    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(message = "用户ID不能为空")
        private Long userId;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        /**
         * 用户类型关系列表
         */
        private List<UserTypeRel> userTypeRelList;

    }
}
